import { ref, computed } from 'vue';

export interface CartItem {
  id: number;
  name: string;
  price: number;
  count: number;
  image: string;
  specs?: string;
  specKey: string;
}

export function useCart() {
  const cartItems = ref<CartItem[]>([]);
  const showCart = ref(false);

  // 计算总数量
  const totalCount = computed(() => 
    cartItems.value.reduce((sum, item) => sum + item.count, 0)
  );

  // 计算总价
  const totalPrice = computed(() => 
    cartItems.value.reduce((sum, item) => sum + item.price * item.count, 0)
  );

  // 添加到购物车
  const addToCart = (product: any, specs?: string) => {
    const specKey = specs ? `${product.id}-${specs}` : `${product.id}`;
    const existItem = cartItems.value.find(item => item.specKey === specKey);
    
    if (existItem) {
      existItem.count++;
    } else {
      cartItems.value.push({
        id: product.id,
        name: product.name,
        price: product.price,
        count: 1,
        image: product.image,
        specs: specs || '',
        specKey: specKey
      });
    }
  };

  // 增加数量
  const increaseItem = (item: CartItem) => {
    item.count++;
  };

  // 减少数量
  const decreaseItem = (item: CartItem) => {
    if (item.count > 1) {
      item.count--;
    } else {
      const index = cartItems.value.findIndex(i => i.specKey === item.specKey);
      if (index > -1) {
        cartItems.value.splice(index, 1);
      }
    }
  };

  // 获取商品在购物车中的数量
  const getProductCount = (productId: number) => {
    return cartItems.value
      .filter(item => item.id === productId)
      .reduce((sum, item) => sum + item.count, 0);
  };

  // 获取分类商品总数
  const getCategoryCount = (category: any) => {
    return cartItems.value
      .filter(item => category.products.some((p: any) => p.id === item.id))
      .reduce((sum, item) => sum + item.count, 0);
  };

  // 切换购物车显示
  const toggleCart = () => {
    if (totalCount.value === 0) return;
    showCart.value = !showCart.value;
  };

  // 清空购物车
  const clearCart = () => {
    uni.showModal({
      title: '提示',
      content: '确定清空购物车吗?',
      success: (res) => {
        if (res.confirm) {
          cartItems.value = [];
          showCart.value = false;
        }
      }
    });
  };

  return {
    cartItems,
    showCart,
    totalCount,
    totalPrice,
    addToCart,
    increaseItem,
    decreaseItem,
    getProductCount,
    getCategoryCount,
    toggleCart,
    clearCart
  };
}